package com.yang.common.core.retry;

import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Supplier;

/**
 * @author: Billyang
 * @date: 2024/9/8 17:09
 */
@Slf4j
@Builder
@Data
public class RetryTemplate {
    /*
      重试次数
     */
    private int retryTimes;
    /*
    初始重试间隔时间ms
     */
    private long delayMillis;
    /*
    最大重试间隔时间ms
     */
    private long maxDelayMillis;

    public <T> T execute(Supplier<T> supplier) throws InterruptedException {
        int retryCount = 0;
        do {
            try {
                return supplier.get();
            } catch (Exception e) {
                if (retryCount >= retryTimes) {
                    throw e;
                }
            }
            retryCount++;
            long waitTime = Math.min(maxDelayMillis, delayMillis * retryCount);
            log.info("RetryTemplate execute waitTime:{}ms,retryCount:{}", waitTime, retryCount);
            Thread.sleep(waitTime);
        } while (retryCount <= retryTimes);
        return null;
    }
}
